module LockDown
  module Controller
    def check_for_permission
      unless access_approved?("/" + params[:controller], params[:action], params[:id])
        if session[:redirect_try]
          goto = session[:redirect_try].dup
          session[:redirect_try] = nil
        else
          goto = denied_url
        end
        redirect_to(goto) 
        return
      end
    end
    
    def access_approved?(ctroller, action, id = nil)
      return true if allow_request?(ctroller, action)

      session[:allowed_urls].each do |hsh|
        id = id.to_i if id
        if (ctroller == hsh[:controller]) && (action == hsh[:action]) && (id == hsh[:id])
          setup_redirect
          return true 
        end
      end if session[:allowed_urls]

      return false
    end

    private
      def setup_redirect
        return unless session[:allowed_urls]
        session[:allowed_urls].each do |au|
          if session[:prevpage] == au[:controller] + "/" + au[:action] + "/" + au[:id].to_s
            return 
          end
        end
        session[:redirect_try] = session[:prevpage] 
      end
      
      def allow_request?(ctroller,action)
        #Allow for home page access until session is setup.  Initial
        #request calls this before_filter before the application_controller
        #before_filter.  This is also needed on logout functionality, because
        #it clears the session
        return true if ctroller == "home" && action =="index"

        session[:permissions] = LockDown.public_actions unless session[:permissions]

        session[:permissions].each do |perm|
          return true if perm ==  LockDown.format_controller_action(ctroller,action)
        end

        return false
      end
  end # Controller
end # LockDown

ActionController::Base.send :include, LockDown::Controller

